package com.control.qct.businesssteward.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.control.qct.businesssteward.R;
import com.control.qct.businesssteward.base.BaseBean;
import com.control.qct.businesssteward.base.BaseFragment;
import com.control.qct.businesssteward.httputils.HttpUtils;
import com.control.qct.businesssteward.model.DoPayGoodsModel;
import com.control.qct.businesssteward.model.PaymentStyleModel;
import com.control.qct.businesssteward.utils.CustomCodeUtils;
import com.control.qct.businesssteward.utils.GlideUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/12/3 0003.
 */

@SuppressLint("ValidFragment")
public class PaymentScanFragment extends BaseFragment implements HttpUtils.IHttpResult, CustomCodeUtils
        .ICallbackListener {
    @BindView(R.id.tv_scan_customer_code)
    TextView mTvScanCustomerCode;
    @BindView(R.id.tv_gathering_name)
    TextView mTvGatheringName;
    @BindView(R.id.iv_code)
    ImageView mIvCode;

    private Map<String, String> mParams;
    private DoPayGoodsModel mDoPayGoodsModel;
    private PaymentStyleModel paymentStyleBeans;
    private double amount;
    private boolean isCode;
    private IPaymentCallbackResult mIPaymentCallbackResult;
    private int payType;
    private int mPayType;
    private TimerTask mTimerTask;
    private Timer mTimer;

    public PaymentScanFragment(DoPayGoodsModel doPayGoodsModel, PaymentStyleModel paymentStyleBeans, double amount,
                               IPaymentCallbackResult listener) {
        mDoPayGoodsModel = doPayGoodsModel;
        this.paymentStyleBeans = paymentStyleBeans;
        this.amount = amount;
        mIPaymentCallbackResult = listener;
    }

    @Override
    protected View initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        return inflater.inflate(R.layout.fragment_payment_scan, container, false);
    }

    @Override
    protected void initView(View view) {
        activity.setLeftIcon(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.getSupportFragmentManager().popBackStack();
            }
        });
        switch (paymentStyleBeans.getGroupNo()) {
            case 2://支付宝
                payType = 24;
                doPayScanZFBByBuyer();
                break;
            case 4://智能码
                payType = 18;
                doPayScanByBuyer();
                break;
            case 6://微信
                payType = 26;
                doPayScanWXByBuyer();
                break;
        }
    }


    @OnClick(R.id.tv_scan_customer_code)
    public void onViewClicked() {
        CustomCodeUtils.getInstance(activity).startToCaptureActivity(this);
    }


    /**
     * 聚合支付被扫
     */
    private void doPayScanByBuyer() {
        mParams = new HashMap<>();
        mParams.put("orderId", mDoPayGoodsModel.getOrderId());
        mParams.put("amount", amount + "");
        mParams.put("payGroupCode", paymentStyleBeans.getGroupNo() + "");
        mNetProtocol.doPayScanByBuyer(activity, mParams, this);
    }

    /**
     * 聚合支付主扫
     */
    private void doPayScanByCode(String payToken) {
        mParams = new HashMap<>();
        mParams.put("orderId", mDoPayGoodsModel.getOrderId());
        mParams.put("amount", amount + "");
        mParams.put("payToken", payToken);
        mParams.put("payGroupCode", paymentStyleBeans.getGroupNo() + "");
        mNetProtocol.doPayScanByCode(activity, mParams, this);
    }

    /**
     * 支付宝被扫
     */
    private void doPayScanZFBByBuyer() {
        mParams = new HashMap<>();
        mParams.put("orderId", mDoPayGoodsModel.getOrderId());
        mParams.put("orderSn", mDoPayGoodsModel.getOrderSn());
        mParams.put("amount", amount + "");
        mParams.put("payGroupCode", paymentStyleBeans.getGroupNo() + "");
        mNetProtocol.doPayScanZFBByBuyer(activity, mParams, this);
    }

    /**
     * 支付宝主扫
     */
    private void doPayScanZFBByCode(String payToken) {
        mParams = new HashMap<>();
        mParams.put("orderId", mDoPayGoodsModel.getOrderId());
        mParams.put("orderSn", mDoPayGoodsModel.getOrderSn());
        mParams.put("amount", amount + "");
        mParams.put("payToken", payToken);
        mParams.put("payGroupCode", paymentStyleBeans.getGroupNo() + "");
        mNetProtocol.doPayScanZFBByCode(activity, mParams, this);
    }

    /**
     * 微信被扫
     */
    private void doPayScanWXByBuyer() {
        mParams = new HashMap<>();
        mParams.put("orderId", mDoPayGoodsModel.getOrderId());
        mParams.put("orderSn", mDoPayGoodsModel.getOrderSn());
        mParams.put("amount", amount + "");
        mParams.put("payGroupCode", paymentStyleBeans.getGroupNo() + "");
        mNetProtocol.doPayScanWXByBuyer(activity, mParams, this);
    }

    /**
     * 微信主扫
     */
    private void doPayScanWXByCode(String payToken) {
        mParams = new HashMap<>();
        mParams.put("orderId", mDoPayGoodsModel.getOrderId());
        mParams.put("orderSn", mDoPayGoodsModel.getOrderSn());
        mParams.put("amount", amount + "");
        mParams.put("payToken", payToken);
        mParams.put("payGroupCode", paymentStyleBeans.getGroupNo() + "");
        mNetProtocol.doPayScanWXByCode(activity, mParams, this);
    }

    /**
     * 获取支付被扫结果
     *
     * @param payType
     */
    private void getPayResult(String payType) {
        mParams = new HashMap<>();
        mParams.put("orderId", mDoPayGoodsModel.getOrderId());
        mParams.put("payType", payType);
        mNetProtocol.getPayResult(activity, mParams,false, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                if (((Double) baseBean.getData()) == 1) {
                    mIPaymentCallbackResult.onResult("", mPayType);
                    showShortToast("支付成功！");
                    activity.getSupportFragmentManager().popBackStack();
                }
            }

            @Override
            public void onFail(BaseBean baseBean) {

            }
        });
    }

    /**
     * 轮询查询被扫支付结果
     */
    private void doPayGetResult() {
        for (int i = 0; i < paymentStyleBeans.getItems().size(); i++) {
            if (paymentStyleBeans.getItems().get(i).getTitle().contains("被扫")) {
                mPayType = paymentStyleBeans.getItems().get(i).getPayType();
            }
        }
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                getPayResult(mPayType + "");
            }
        };
        mTimer.schedule(mTimerTask, 1000,1000);
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        if (!isCode) {
            GlideUtil.loadImage(this, baseBean.getMessage(), mIvCode);
            doPayGetResult();
        } else {
            mIPaymentCallbackResult.onResult(baseBean.getMessage(), payType);
            activity.getSupportFragmentManager().popBackStack();
        }
    }

    @Override
    public void onFail(BaseBean baseBean) {
        if (!isCode) {
            showShortToast("商户订单号重复！");
        } else {
            showShortToast(baseBean.getMessage());
        }
        activity.getSupportFragmentManager().popBackStack();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CustomCodeUtils.REQUEST_CODE:
                CustomCodeUtils.getInstance(activity).onCallBackListener(requestCode, data, this);
                break;
        }
    }

    @Override
    public void onCallbackListener(String result) {
        isCode = true;
        switch (paymentStyleBeans.getGroupNo()) {
            case 2://支付宝
                payType = 23;
                doPayScanZFBByCode(result);
                break;
            case 4://智能码
                payType = 19;
                doPayScanByCode(result);
                break;
            case 6://微信
                payType = 25;
                doPayScanWXByCode(result);
                break;
        }
    }


    /**
     * 返回支付结果
     */
    public interface IPaymentCallbackResult {
        void onResult(String tradeNo, int payType);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
}
